package org.zjx.app.action.login;


import org.zjx.analysis.analyze.login.LoginRoleAnalysis;
import org.zjx.command.state.AccountState;
import org.zjx.window.action.Action;
import org.zjx.window.operation.WindowOperation;
import org.zjx.window.window.IWindow;

import java.awt.*;

public class LoginRoleAction extends Action { // 在需要的时候才进行详细分析
    protected LoginRoleAnalysis loginRoleAnalysis;

    public LoginRoleAction(IWindow targetWindow) {
        super(targetWindow, false);
        loginRoleAnalysis = new LoginRoleAnalysis();
        loginRoleAnalysis.analyze(targetWindow.getScreenshot());
    }

    @Override
    protected void doExecute() throws Exception {
        AccountState accountState = targetWindow.getState().getState(AccountState.class);
        if (accountState.getPlayerId().isEmpty()) {
            Rectangle createButtonRectangle = loginRoleAnalysis.getCreateButtonRectangle(targetWindow.getScreenshot());
            targetWindow.actions().clickAt(createButtonRectangle.getCenterX(), createButtonRectangle.getCenterY());
        } else {
            String playerId = accountState.getPlayerId();
            String chooseId = loginRoleAnalysis.getChooseId(this.targetWindow.getScreenshot());
            if (playerId.equals(chooseId)) {
                Rectangle inButtonRectangle = loginRoleAnalysis.getInButtonRectangle(targetWindow.getScreenshot());
                targetWindow.actions().clickAt(inButtonRectangle.getCenterX(), inButtonRectangle.getCenterY());
            } else {
                int chooseRolePosition = loginRoleAnalysis.chooseRolePosition(targetWindow.getScreenshot());
                Rectangle nextRoleRectangle = loginRoleAnalysis.getNextRoleRectangle(targetWindow.getScreenshot(), chooseRolePosition);
                if (chooseRolePosition == 5 || nextRoleRectangle == null) {
                    throw new UnsupportedOperationException("该服务器没有指定角色:" + playerId);
                } else {
                    targetWindow.actions().clickAt(nextRoleRectangle.getCenterX(), nextRoleRectangle.getCenterY());
                }
            }
        }
        targetWindow.execute(WindowOperation.delay(500));
    }
}
